from django.shortcuts import render_to_response
from django.shortcuts import redirect, render, get_object_or_404

from django.http import HttpResponseRedirect 
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
from accounts.forms import ProfileForm 
from django.template import RequestContext
from .models import Profile

def register(request):
    if request.method == "POST":
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save(True)
            user = authenticate(username=user.username, password=form.cleaned_data.get('password2'))
            login(request, user)
            return HttpResponseRedirect("/")
    else:
        form = UserCreationForm()
        return render_to_response("register.html", {"form":form}, 
            context_instance=RequestContext(request))

def user_profile(request, username):
    u = get_object_or_404(User, username=username)
    ctx = {
        'user_obj': u,
        'email_hash': hashlib.md5(u.email).hexdigest(),
        'user_can_commit': u.has_perm('auth.commit'),
        'clas': find_agreements(u),
        'stats': get_user_stats(u),
    }
    return render(request, "user_profile.html", ctx)

@login_required
def edit_profile(request):
    profile, created = Profile.objects.get_or_create(user=request.user)
    form = ProfileForm(request.POST or None, instance=profile)
    if form.is_valid():
        form.save()
        return HttpResponseRedirect('/')

    return render(request, "edit_profile.html", {'form': form})
